package com.fjwt.gz.db.typehandler;


import com.fjwt.gz.db.dto.PointDTO;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * Point  类型处理器
 */
@Component
public class PointTypeHandler extends BaseTypeHandler<PointDTO> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PointDTO location, JdbcType jdbcType) throws SQLException {
        String wkt = String.format("POINT(%f %f)", location.getLongitude(), location.getLatitude());
        ps.setString(i, wkt);
    }

    @Override
    public PointDTO getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkt = rs.getString(columnName);
        return parseWKT(wkt);
    }

    @Override
    public PointDTO getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkt = rs.getString(columnIndex);
        return parseWKT(wkt);
    }

    @Override
    public PointDTO getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkt = cs.getString(columnIndex);
        return parseWKT(wkt);
    }

    private PointDTO parseWKT(String wkt) {
        if (wkt == null || !wkt.startsWith("POINT")) return null;

        String[] parts = wkt.replaceAll("[^\\d\\.\\-\\s]", "").trim().split("\\s+");
        if (parts.length != 2) return null;

        double longitude = Double.parseDouble(parts[0]);
        double latitude = Double.parseDouble(parts[1]);

        return new PointDTO(new BigDecimal(String.valueOf(longitude)), new BigDecimal(String.valueOf(latitude)));
    }
}
